import { updateStorage } from "@/utils";
import request from "@/utils/request";

let userInfo = localStorage.getItem("userInfo");
try {
  userInfo = JSON.parse(userInfo) || {};
} catch (err) {
  userInfo = {};
}
// console.log('userInfo',userInfo.ret.username);
export default {
  // 启用命名空间
  namespaced: true,
  state: {
    userInfo,
  },
  getters: {
    isLogin(state) {
      // state： 当前模块的state
      // getters: 当前模块的getters
      // rootState: 全局状态（包含所有模块的状态）
      // rootGetters: 全局getters（包含所有模块的getters）
      // console.log('user->state,getters,rootState,rootGetters',state,getters,rootState,rootGetters)
      // return !!state.userInfo.authorization
      // console.log('aaaaa',state.userInfo); //没有设置token就不拿令牌

      //判断
      // console.log("state.userInfo:",state.userInfo.authorization);
      return !!state.userInfo.authorization;
    },
  },
  mutations: {
    login(state, payload) {
      state.userInfo = payload;
      console.log(payload);
      updateStorage("userInfo", payload);
    },
    logout(state) {
      state.userInfo = {};
      localStorage.removeItem("userInfo");
    },
  },
  actions: {
    //context相当于$state
    async login(context, payload) {
      // context={state,getters,commit,dispatch}
      // console.log('context',context,payload);
      const { data } = await request.post("/admin/login", payload);
      // console.log(data);
      if (data.code === 200) {
        context.commit("login", data);
        // context.commit('addAuthRouter',null,{root:true})
        // console.log(data,'data');
        context.commit(
          {
            type: "addAuthRouter",
            // payload:
          },
          { root: true }
        );
        console.log("okkok");
      }

      return data;
    },
  },
};
